# -*- coding: utf-8 -*-
import hashlib
import json
import random
import time
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '100421': {  # FFPAY 支付宝扫码 2.4% 10-5000 dwc
        'API_KEY': '521D4D21CB4FBDAB6279244914D22620',
        'gateway': 'https://www.ffpay.net/api/pay',
        'query_gateway': 'https://www.ffpay.net/api/orderquery',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().lower()
    return sign


def generate_sign(d, key):
    s = 'Amount={}&BankCode={}&Ip={}&MerchantCode={}&NotifyUrl={}&OrderDate={}&OrderId={}&Key={}'.format(
        d['Amount'], d['BankCode'], d['Ip'], d['MerchantCode'], d['NotifyUrl'], d['OrderDate'], d['OrderId'], key)
    return _gen_sign(s)


def generate_create_response_sign(d, api_key):
    sd = ''
    for key in sorted(d['data']):
        sd += '"' + key + '":' + '"' + d['data'][key] + '",'
    sd = '{' + sd[:len(sd) - 1] + '}'
    s = 'data={}&date={}&merchantCode={}&orderId={}&key={}'.format(sd,
                                                                   d['date'], d['merchantCode'], d['orderId'], api_key)
    return _gen_sign(s)


def generate_notify_sign(d, key):
    s = 'Amount={}&BankCode={}&MerchantCode={}&OrderDate={}&OrderId={}&OutTradeNo={}&Status={}&Time={}&Key={}'.format(
        d['Amount'], d['BankCode'], d['MerchantCode'], d['OrderDate'], d['OrderId'], d['OutTradeNo'], d['Status'],
        d['Time'], key)
    return _gen_sign(s)


def generate_query_sign(d, key):
    s = 'MerchantCode={}&OrderId={}&Time={}&Key={}'.format(
        d['MerchantCode'], d['OrderId'], d['Time'], key)
    return _gen_sign(s)


def verify_sign(params, key):
    sign = params['data']['sign']
    params['data'].pop('sign')
    calculated_sign = generate_create_response_sign(params['data'], key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("ffpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def verify_notify_sign(params, key):
    sign = params['Sign']
    params.pop('Sign')
    calculated_sign = generate_notify_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("ffpay notify sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '58.64.207.179'


def _get_pay_type(service):
    if service == 'alipay':
        return 'ALIPAY'
    return 'ALIPAY'


def _fix_pay_amount(pay, pay_amount):
    extend = json.loads(pay.extend or '{}')
    if 10 <= pay_amount == int(pay_amount):
        discount = random.randint(1, 10)
        pay_amount = pay_amount - float(discount) / 100
        extend.update({'discount': str(float(discount) / 100)})
        order_db.fill_extend(pay.id, extend)
    return pay_amount


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    # pay_amount = _fix_pay_amount(pay, pay_amount)
    parameter_dict = OrderedDict((
        ('MerchantCode', app_id),
        ('BankCode', _get_pay_type(service)),
        ('Amount', '%.2f' % pay_amount),
        ('OrderId', str(pay.id)),
        ('NotifyUrl', '{}/pay/api/{}/ffpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('OrderDate', int(round(time.time() * 1000))),
        ('Ip', _get_device_ip(service)),
        ('Remark', 'charge'),
    ))
    parameter_dict['Sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("ffpay create: %s, order_id is: %s", json.dumps(parameter_dict), parameter_dict['OrderId'])
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_gateway(app_id), data=parameter_dict, headers=headers, timeout=3, verify=False)
    res_obj = json.loads(response.text)
    _LOGGER.info("ffpay create charge response.text: %s", response.text)
    verify_sign(res_obj, api_key)
    return {'charge_info': res_obj['data']['data']['info']}


# success
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    data = dict(request.POST.iteritems())
    _LOGGER.info("ffpay notify data: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['OrderId']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('ffpay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['Status'])
    trade_no = data['OutTradeNo']
    total_fee = float(data['Amount'])
    discount = float(json.loads(pay.extend or '{}').get('discount', 0))
    extend = {
        'discount': discount,
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    # 0:处理中, 1:成功, 0:失败
    if trade_status == '1':
        _LOGGER.info('ffpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('MerchantCode', app_id),
        ('OrderId', str(pay_order.id)),
        ('Time', int(round(time.time() * 1000))),
    ))
    parameter_dict['Sign'] = generate_query_sign(parameter_dict, api_key)
    _LOGGER.info('ffpay query data, %s', parameter_dict)
    _LOGGER.info('ffpay query order_is is: %s', parameter_dict['OrderId'])
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(app_id), data=parameter_dict, headers=headers, timeout=3, verify=False)
    _LOGGER.info('ffpay query rsp, %s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)['data']
        mch_id = pay_order.mch_id
        trade_status = str(data['data']['status'])
        total_fee = float(data['data']['moneyReceived'])
        trade_no = pay_order.third_id

        discount = float(json.loads(pay_order.extend or '{}').get('discount', 0))
        extend = {
            'discount': discount,
            'trade_status': trade_status,
            'total_fee': total_fee,
            'trade_no': trade_no,
        }
        # 订单状态 0待处理，1完成，2失败
        if trade_status == '1':
            _LOGGER.info('ffpay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
